package com.ruoyi.web.core.netty;

import com.github.misterchangray.core.MagicByte;
import com.ruoyi.web.core.receive.CheckUpdateReceiveMagicDTO;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.swagger.models.auth.In;

import java.util.List;

/**
 * @ClassName MyDecoder @Deacription TODO netty接收对象转16进制 @Author LiuDaGang @Date 2021/3/2
 * 14:49 @Version 1.0
 */
public class HexDecoder extends ByteToMessageDecoder {

  @Override
  protected void decode(
      ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list)
      throws Exception {
    // 创建字节数组,buffer.readableBytes可读字节长度
    byte[] b = new byte[byteBuf.readableBytes()];
    // 复制内容到字节数组b
    byteBuf.readBytes(b);
    // 字节数组转字符串
    String str = new String(b);

    // System.out.println(str);

    list.add(bytesToHexString(b));
  }

  /**
   * 简洁写法 16进制字符串转成byte数组
   * @param hex 16进制字符串，支持大小写
   * @return byte数组
   */
  public static byte[] hexStringToBytes(String hex) {
    byte[] bytes = new byte[hex.length() / 2];
    for (int i = 0; i < bytes.length; i++) {
      bytes[i] = (byte) Integer.parseInt(hex.substring(i * 2, i * 2 + 2), 16);
    }
    return bytes;
  }

  /**
   * 简洁写法 byte数组转成16进制字符串
   * @param bytes byte数组
   * @return 16进制字符串
   */
  public static String bytesToHexString(byte[] bytes) {
    StringBuilder builder = new StringBuilder();
    for (byte b : bytes) {
      builder.append(String.format("%02X", b));
    }
    return builder.toString();
  }

  public static void main(String[] args) {

    String a = "4901043883131350000000000000000000050696665506164000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000074655F32303233303931343133353231334130303853230323330393135313135343137413030310000000000003230323330393134000000000000000000000000000000000000000000000000000000000000000000000000000000000000";
    int i1 = Integer.parseInt(a.trim(), 16);
    long i = Long.parseLong(a);

    String str = "3100000000000000000000000200506C75736C696665506164000000000000000000000000000000000000000000000000000000000000000000000000000000E8033132333435360000000000000000000000005356342E302E350000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000";

    byte[] bytes1 = hexStringToBytes(str);
    System.out.println(MagicByte.pack(bytes1, CheckUpdateReceiveMagicDTO.class).toString());
  }
}
